<template>
  <div class="UserList-page searchAdapt-Four innerPageTable-out-flex">
    <!-- <PageTable v-if="dataReady" ref="userTable" :config="pageTableConfig"></PageTable> -->
    <!-- 搜索区域 -->
    <SelfAdaption v-if="!useTableSearchBar">
      <!-- Search bar -->
      <Form
        v-if="USER_QUERY"
        :model="formSearch"
        ref="userFormSearch"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 用户账号 -->
          <Form-item prop="userId" :label="$t('module.userManage.userAccount')">
            <Input
              type="text"
              v-model.trim="formSearch.userId"
              :placeholder="$t('module.userManage.placeholder.account')"
              @on-enter="searchInfo"
            ></Input>
          </Form-item>

          <!-- 用户名称 -->
          <Form-item prop="userName" :label="$t('module.userManage.name')">
            <Input
              type="text"
              v-model.trim="formSearch.userName"
              :placeholder="$t('module.userManage.placeholder.userName')"
              @on-enter="searchInfo"
              :maxlength="30"
            ></Input>
          </Form-item>

          <!-- 手机号码 -->
          <Form-item prop="mobile" :label="$t('module.userManage.cellPhoneNumber')">
            <Input
              type="text"
              v-model.trim="formSearch.mobile"
              :placeholder="$t('module.userManage.placeholder.phoneNumber')"
              @on-enter="searchInfo"
              :maxlength="11"
            ></Input>
          </Form-item>

          <!-- 电子邮箱 -->
          <Form-item prop="email" :label="$t('module.userManage.email')">
            <Input
              type="text"
              v-model.trim="formSearch.email"
              :placeholder="$t('module.userManage.placeholder.email')"
              @on-enter="searchInfo"
            ></Input>
          </Form-item>

          <!-- 状态 -->
          <Form-item prop="locked" :label="$t('common.status')">
            <Select
              v-model="formSearch.locked"
              style="width: 100%;"
              clearable
              :placeholder="$t('common.warning.selectStatus')"
            >
              <Option v-for="item in searchStatusList" :value="item.vsiKey" :key="item.vsiKey">{{
                item.vsiValue
              }}</Option>
            </Select>
          </Form-item>

          <!-- 角色编码 -->
          <!-- <Form-item prop="roleCode" :label="$t('module.userManage.roleCode')">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="formSearch.roleCode"
              :placeholder="$t('module.userManage.placeholder.enterRoleCode')"
              
              @on-enter="searchInfo"
            ></Input>
          </Form-item>-->

          <!-- 所属组织 -->
          <Form-item prop="orgName" :label="$t('module.userManage.organization')">
            <Input
              type="text"
              style="position: absolute; z-index: 999; width: 80%; opacity: 0;"
              @click.native="selectOrganization"
            ></Input>
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="formSearch.orgName"
              :placeholder="$t('module.userManage.selectOrganization')"
              icon="ios-paper-plane-outline"
              clearable
              readonly
              @on-clear="resetOrganization"
              @on-click="selectOrganization"
            ></Input>
          </Form-item>

          <!-- 查询\重置按钮 -->
          <Form-item prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="searchInfo" />
            <RPButton optType="reset" @click="formReset" />
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="userTable" :config="pageTableConfig" v-if="USER_QUERY">
      <div slot="table-bar">
        <RPButton optType="create" @click="createUserInfo" />
        <RPButton optType="create" @click="createLdap" :text="$t('module.userManage.ldapcreate')" />
        <RPButton optType="batch" @click="deleteUser" />
      </div>
      <Form
        v-if="USER_QUERY && useTableSearchBar"
        :model="formSearch"
        ref="userFormSearch"
        slot="table-search-bar"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 所属组织 -->
          <Form-item prop="orgName">
            <Input
              type="text"
              style="position: absolute; z-index: 999; width: 80%; opacity: 0;"
              @click.native="selectOrganization"
            ></Input>
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="formSearch.orgName"
              :placeholder="$t('module.userManage.selectOrganization')"
              icon="ios-paper-plane-outline"
              clearable
              readonly
              @on-clear="resetOrganization"
              @on-click="selectOrganization"
            ></Input>
          </Form-item>
          <!-- 状态 -->
          <Form-item prop="locked">
            <Select
              v-model="formSearch.locked"
              style="width: 150px"
              clearable
              @on-change="searchInfo"
              :placeholder="$t('common.warning.selectStatus')"
            >
              <Option v-for="item in searchStatusList" :value="item.vsiKey" :key="item.vsiKey">{{
                item.vsiValue
              }}</Option>
            </Select>
          </Form-item>
          <Form-item prop="searchType">
            <Input
              type="text"
              v-model.trim="formSearch.searchTypeValue"
              :placeholder="searchTypePlaceholder"
              @on-enter="searchInfo"
              @on-blur="searchInfo"
            >
            <template #prepend>
              <Select v-model="formSearch.searchType" style="width: 110px" @on-change="searchTypeChange">
                <Option v-for="item in searchTypeList" :value="item.key" :key="item.key">{{
                item.name
              }}</Option>
              </Select>
            </template>
            </Input>
          </Form-item>
        </template>
      </Form>
    </InnerPageTable>
  </div>
</template>
<script>
import locales from './locales.js'
import UserEdit from './UserEdit.vue'
import LdapManage from './LdapManage.vue'

import UnlockManage from './UnlockManage.vue'
import ExternalAccount from './ExternalAccount.vue'
import selectOrganization from './selectOrganization.vue'
import { generateColumns } from './colomns'
import tenantAPI from '@/api/tenantApi.js'
import valueSetAPI from '@/api/valueSetAPI.js'

import userManageAPI from '@/api/userManageApi'
import { queryOrgsByOrgPaths } from '@/api/orgApi'
import { CoreModuleName } from '@/const'

const RIPPLES = 'ripples'
export default {
  name: 'user-list',
  mixins: [locales],
  data() {
    return {
      useTableSearchBar: false,
      currentUserInfo: $store.state[CoreModuleName].userInfo,
      dataReady: false,
      isAdmin:
        $store.state[CoreModuleName].userInfo.category == '1' || $store.state[CoreModuleName].userInfo.category == '2',
      searchStatusList: [], //状态下拉框数据
      searchTypeList: [
        {key: 'userId',  name: this.$t('module.userManage.userAccount'), placeholder: this.$t('module.userManage.placeholder.account')},
        {key: 'userName',  name: this.$t('module.userManage.name'), placeholder: this.$t('module.userManage.placeholder.userName')},
        {key: 'mobile',  name: this.$t('module.userManage.cellPhoneNumber'), placeholder: this.$t('module.userManage.placeholder.phoneNumber')},
        {key: 'email',  name: this.$t('module.userManage.email'), placeholder: this.$t('module.userManage.placeholder.email')}
      ],
      searchTypePlaceholder: this.$t('module.userManage.placeholder.account'),
      formSearch: {
        userId: '',
        userName: '',
        mobile: '',
        email: '',
        roleCode: '', // 角色编码
        locked: 'ALL', //状态
        orgName: '',
        orgId: '',
        searchType: 'userId',
        searchTypeValue: '',
      },
      tenantList: {},
      pageTableConfig: {
        loadDataFn: this.getUserListPage,
        columns: generateColumns.bind(this)(),
        autoFirst: true,
        selectionAreaItem: { key: "id", title: "userName" },
        allSelection: [],
        tableSearchBar: true,
        simplePage: true
      },
      sourceList: {},
      disabledDeleteUserBtn: false
    };
  },
  created() {
    this.hiddenRoleNames()
    this.addColomns()
    this.getStateSelect()
    this.initData()
    this.getSourceInfo()
    if (this.is_Digitalplatform) {
      // 隐藏 ”所分配角色“字段
      this.pageTableConfig.columns = this.pageTableConfig.columns.filter(items => items.key !== 'roleNames')
    } else {
      // 隐藏 “所属租户”字段， 显示 ”所分配角色“字段
      this.pageTableConfig.columns = this.pageTableConfig.columns.filter(items => items.key !== 'tenantCode')
    }
  },
  computed: {
    USER_QUERY() {
      return $util.checkPermission('USER_INDEX') || $util.checkPermission('ACCESSIBLE_APP') //用户查询UI资源 授权
    },
    USER_DETAIL() {
      return $util.checkPermission('USER_INDEX') //用户详情UI资源  授权
    },
    ACCESSIBLE_APP() {
      return $util.checkPermission('ACCESSIBLE_APP') //可访问应用UI资源 授权
    },
    category() {
      let platformAdmin = this.$t('module.userManage.platformAdmin')
      let tenantAdmin = this.$t('module.userManage.tenantAdmin')
      let ordinaryUser = this.$t('module.userManage.ordinaryUser')
      // 用户类型数据: ["", "平台管理员", "租户管理员", "普通用户"]
      return ['', platformAdmin, tenantAdmin, ordinaryUser]
    },
    // 判断是否是数字化平台：1. 所属租户是数字化平台; 2. 用户类型是平台管理员或者租户管理员
    is_Digitalplatform() {
      // 当前登录用户
      let currentUserInfo = this.currentUserInfo
      let curTenantCode = currentUserInfo.tenantCode && currentUserInfo.tenantCode.toLowerCase() === RIPPLES
      let curUserCategory = currentUserInfo.category // 用户类型: 1. 平台管理员 2. 租户管理员 3. 普通用户
      if (curTenantCode) {
        return true
      } else {
        return false
      }
    },
    searchParams() {
      let _formSearch = Object.assign({}, this.formSearch)
      // 状态数据是通过值集查的，后端没有保持统一，所有前端这里处理
      if(this.useTableSearchBar) {
        this.searchTypeList.forEach(item => {
          if (this.formSearch.searchType == item.key) {
            _formSearch[item.key] = this.formSearch.searchTypeValue
          } else {
            _formSearch[item.key] = ''
          }
        })
      }
      delete _formSearch.searchType
      delete _formSearch.searchTypeValue
      let _result = ''
      switch (_formSearch.locked) {
        case 'ALL':
          _result = ''
          break
        case '0':
          _result = 1
          break
        case '1':
          _result = 0
          break
      }
      _formSearch.locked = _result
      return _formSearch
    }
  },
  methods: {
    searchTypeChange() {
      if (this.formSearch.searchTypeValue) {
        this.searchInfo()
      }
    },
    // 选择组所属组织
    selectOrganization() {
      new this.$pageModal(
        selectOrganization,
        {
          props: {}
        },
        data => {
          if (data) {
            this.formSearch.orgName = data.orgName
            this.formSearch.orgId = data.orgId
            this.searchInfo()
          }
        }
      )
    },
    // 获取状态下拉数据
    async getStateSelect() {
      const [searchStatusList] = await Promise.all([valueSetAPI.getValueSetByCode('ENABLED_CODE')])
      searchStatusList.map((item, index) => {
        if (item.vsiKey == 'ALL') {
          searchStatusList.splice(index, 1)
        }
      })
      this.searchStatusList = searchStatusList
    },
    async initData() {
      const records = await tenantAPI.queryAllTenantList()

      for (const tenant of records) {
        this.tenantList[tenant.tenantCode] = tenant.tenantName
      }

      this.dataReady = true
    },
    // 通过 tenantCode 获取对应的名称
    getTenantName(data) {
      return this.tenantList[data.tenantCode] ? this.tenantList[data.tenantCode] : data.tenantCode
    },
    // 获取用户来源
    getSourceName(type) {
      return this.sourceList[type] || type
    },
    // 所分配角色
    switchRoleName(roleNames) {
      return roleNames ? roleNames.join(';') : ''
    },
    // 格式化用户类型 1: 平台管理员 2: 租户管理员 3: 普通用户
    switchCategory(type) {
      return this.category[type]
    },
    // 列表编辑按钮方法
    editUserInfo(userInfo) {
      this.openEditModel({ userInfo })
    },
    openEditModel(props = {}) {
      new this.$sidelipPage(
        UserEdit,
        {
          props: {
            userInfo: props.userInfo,
            USER_DETAIL: this.USER_DETAIL,
            ACCESSIBLE_APP: this.ACCESSIBLE_APP
          },
          isActionTop: false
        },
        data => {
          if (data) {
            this.search(this.$refs.userTable.param.pageNum)
          }
        }
      )
    },
    // 创建用户
    createUserInfo() {
      this.openEditModel()
    },
    // 搜索查询
    searchInfo() {
      this.$refs['userTable'].load(this.searchParams)
    },
    // 清除所属组织
    resetOrganization() {
      this.formSearch.orgId = ''
      this.formSearch.orgName = ''
      this.searchInfo()
    },
    // 搜索重置
    formReset() {
      this.formSearch.orgId = ''
      this.$refs['userFormSearch'].resetFields()
      this.searchInfo()
      // this.$refs["userTable"].load(this.formSearch);
    },
    // 刷新数据
    search(page = 1) {
      this.$refs['userTable'].load(Object.assign({}, this.searchParams), page)
    },
    // 变更状态
    changeStatus(row) {
      if (row.locked == '0') {
        const isSelf = row.id === this.currentUserInfo.id
        let warningText
        if (isSelf) {
          warningText = this.$t('module.userManage.warning.disableSelf')
        } else {
          warningText = this.$t('module.userManage.warning.disableUser')
        }

        this.$confirm
          .warning(warningText)
          .then(() => {
            this._changeProcess(row, isSelf)
          })
          .catch(_ => _)
      } else {
        //选中后改为有效状态时取消选中
        let delIndex = this.$refs['userTable'].allSelection.findIndex(user => user.id == row.id)
        this.$refs['userTable'].allSelection.splice(delIndex, 1)
        this._changeProcess(row)
      }
    },
    _changeProcess(row, isSelf) {
      userManageAPI.updateStatus(row).then(response => {
        this.$message.success({
          content: this.$t('common.updateSuccess'),
          duration: 3
        })

        if (isSelf) {
          window.$channel.$emit('LoginOut')
        } else {
          this.search(this.$refs.userTable.param.pageNum)
        }
      })
    },
    // 获取来源文案信息
    getSourceInfo() {
      $http
        .get(`${window.RPConfig.setting}/valueset/item/list?vsCode=USER_TYPE`, {})
        .then(response => response.data)
        .then(data => {
          if (data && data.length) {
            let result = {}
            data.some(item => {
              result[item.vsiKey] = item.vsiValue
            })
            this.sourceList = result
          }
        })
    },
    // 如果为租户管理员或者普通用户，列表中显示所属组织
    addColomns() {
      let orgObj = {
        title: this.$t('module.userManage.organization'), // 所属组织
        key: 'orgName',
        minWidth: 110,
        maxWidth: 110 + window.RPConfig.COLUMN_WIDTH.MAX_WIDTH_MORE,
        render: (h, params) => {
          if (params.row._hasOrgInfo) {
            return h(
              'div',
              {
                attrs: {
                  class: 'ivu-table-cell ivu-table-cell-ellipsis',
                  title: params.row.orgNameFullPath
                }
              },
              params.row.orgName
            )
          } else {
            return h('Spin', [
              h('Icon', {
                props: {
                  type: 'ios-loading',
                  size: 18
                },
                class: 'spin-icon-load'
              })
            ])
          }
        }
      }
      this.pageTableConfig.columns.splice(3, 0, orgObj)
    },
    hiddenRoleNames() {
      // 当前登录用户为租户管理员，隐藏表格中的所分配的角色
      // if (this.currentUserInfo.category == 2) {
      //   let index = this.pageTableConfig.columns.findIndex((item, i) => {
      //     return item.key == "roleNames";
      //   });
      //   this.pageTableConfig.columns.splice(index, 1);
      // }
    },
    getUserListPage: tableObj => {
      let { responseProcess, param } = tableObj
      return userManageAPI.getUserListPageNoTotal(param).then(data => {
        //用户类型为自建且无效时可选择，其他情况不可选
        data.records.forEach(item => {
          item._disabled = true;
          // if ((item.type == 1 && item.locked == 1) || (item.type == 5 && item.locked == 1)) {
          if ((item.type == 1 && item.locked == 1) || ([4, 5].includes(item.type) && item.locked == 1)) {
            item._disabled = false;
          }
        })
        let orgPaths = data.records.map(user => {
          return user.orgPath
        })
        if (orgPaths.length > 0) {
          queryOrgsByOrgPaths(orgPaths).then(orgs => {
            data.records.forEach(user => {
              let userOrg = orgs.find(org => {
                return org.orgPath == user.orgPath
              })
              user._hasOrgInfo = true
              if (userOrg) {
                user.orgName = userOrg.orgName
                user.orgNameFullPath = userOrg.orgNameFullPath
              } else {
                user.orgName = user.orgPath
                user.orgNameFullPath = user.orgPath
              }
            })
            responseProcess(data)
          })
        }
        responseProcess(data)
      })
    },
    deleteUser() {
      let allSelected = this.$refs['userTable'].allSelection
      if (allSelected.length == 0) {
        this.$message.error(this.$t('module.userManage.warning.selectDeleteUser'))
        return
      }
      this.$confirm
        .warning(this.$t('module.userManage.warning.deleteUser'))
        .then(() => {
          const ids = allSelected.map(user => user.id)
          const userIds = allSelected.map(user => {
            if (user.type === 5) {
              return user.userId
            }
          })
          userManageAPI.deleteUsers(ids).then(res => {
            this.$message.success({
              content: this.$t('common.deleteSuccess'),
              duration: 3
            })
            let alreadyData = {
              tenantCode: $store.state[CoreModuleName].userInfo.tenantCode,
              userIds
            }
            userManageAPI.alreadydelUser(alreadyData)
            this.$refs['userTable'].allSelection = []
            this.search()
          })
        })
        .catch(_ => _)
    },
    unlock(row) {
      new this.$pageModal(
        UnlockManage,
        {
          props: {
            userId: row.id
          }
        },
        data => {
          this.$refs['userTable'].load(this.searchParams)
        }
      )
    },
    // 新建LADP账号
    createLdap() {
      new this.$sidelipPage(
        LdapManage,
        {
          props: {
            userInfo: {},
            USER_DETAIL: this.USER_DETAIL,
            ACCESSIBLE_APP: this.ACCESSIBLE_APP
          },
          isActionTop: false
        },
        data => {
          this.$refs['userTable'].load(this.searchParams)
        }
      )
    }
  },
  watch: {
    'formSearch.searchType' : {
      handler() {
        let selectItem = this.searchTypeList.find(item => item.key == this.formSearch.searchType)
        this.searchTypePlaceholder =  selectItem ? selectItem.placeholder : ''
      }
    }
  }
}
</script>

<style lang="less">
// @import "../../../styles/searchAdapt-Four.less";
.searchAdapt-Four {
  .ivu-input-icon {
    font-size: 16px !important;
    line-height: 34px !important;
    transform: scaleX(-1);
    transform: scaleX(-1);
    transform: scaleX(-1);
    transform: scaleX(-1);
    cursor: pointer;

    /* IE */
    filter: fliph;
  }

  .search-bar {
    .ivu-form-item-content {
      width: calc(~'100% - 70px');
    }
  }
}

.UserList-page {
  .ivu-spin {
    text-align: left;
  }

  .spin-icon-load {
    transform-origin: 50% calc(50% - 1px);
    animation: ani-demo-spin 1s linear infinite;
  }
}
</style>
